package com.ding.common;

import java.io.*;
import java.net.Socket;

public class MessageChannel extends StreamChannel {


    private BufferedWriter bufferedWriter;
    private BufferedReader bufferedReader;

    private void sendLine(String msg) {
        try {
            bufferedWriter.write(msg);
            bufferedWriter.write("\n");
            bufferedWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
            close();
        }

    }

    private String readLine() {
        try {
            return bufferedReader.readLine();
        } catch (Exception e) {
            close();
            return null;
        }
    }

    public void sendMsg(Message message)  {
        System.out.println("发送消息");
        System.out.println(message);
        sendLine(message.toString());
    }

    public Message readMsg()  {
        String s = readLine();
        System.out.println(s);
        if (s == null) {
            return null;
        }
        Message message = Protocol.parseMassage(s);

        //如果信息时残缺不完整的,就再读一次
        if (message == Protocol.INCOMPLETE_MESSAGE) {
            return readMsg();
        }
        return message;
    }

    public MessageChannel(Socket socket) {
        super(socket);
        if (getSocket() == null) {
            return;
        }
        try {
            this.bufferedReader = new BufferedReader(new InputStreamReader(getSocket().getInputStream()));
            this.bufferedWriter = new BufferedWriter(new OutputStreamWriter(getSocket().getOutputStream()));
        } catch (Exception ignore) {

        }

    }


    @Override
    public void setSocket(Socket socket) {
        super.setSocket(socket);
        if (getSocket() == null) {
            return;
        }
        try {
            this.bufferedReader = new BufferedReader(new InputStreamReader(getSocket().getInputStream()));
            this.bufferedWriter = new BufferedWriter(new OutputStreamWriter(getSocket().getOutputStream()));
        } catch (IOException ignore) {
        }
    }

    @Override
    public void close() {
        super.close();
        this.bufferedReader = null;
        this.bufferedWriter = null;
    }
}
